import { Disciple } from '../domain/Disciple';
import { Detail } from '../domain/Detail';
import { ScoringPeriodService } from './ScoringPeriodService';
import { ScoringPeriod } from '../domain/ScoringPeriod';
import { RecycleBinService } from './RecycleBinService';
import { DateUtil } from '@/utils/DateUtil';

/**
 * 弟子数据管理服务
 * 处理弟子的增删改查和积分操作
 */
export class DiscipleService {
    private static disciples: Disciple[] = [];
    private static storageKey = 'chengzheng_disciples';
    
    /**
     * 初始化服务
     * 加载存储的数据并初始化周期
     */
    static initialize(): void {
      ScoringPeriodService.initializePeriods();
      this.loadFromStorage();
    }
    
    /**
     * 获取所有弟子
     * @returns 弟子列表
     */
    static getAllDisciple(): Disciple[] {
      return [...this.disciples];
    }
    
    /**
     * 根据ID查找弟子
     * @param id 弟子ID
     * @returns 找到的弟子或undefined
     */
    static getDiscipleById(id: string): Disciple | undefined {
      return this.disciples.find(d => d.id === id);
    }
    
    /**
     * 根据代号查找弟子
     * @param code 弟子代号
     * @returns 找到的弟子或undefined
     */
    static getDiscipleByCode(code: string): Disciple | undefined {
      return this.disciples.find(d => d.code === code);
    }
    
    /**
     * 添加新弟子
     * @param disciple 弟子对象
     * @returns 操作结果
     */
    static addDisciple(disciple: Disciple): { success: boolean; message: string } {
      // 检查代号是否重复
      if (this.disciples.some(d => d.code === disciple.code)) {
        return { success: false, message: '弟子代号已存在' };
      }
      
      // 检查姓名是否重复
      if (this.disciples.some(d => d.name === disciple.name)) {
        return { success: false, message: '弟子姓名已存在' };
      }
      
      this.disciples.push(disciple);
      this.saveToStorage();
      return { success: true, message: '添加成功' };
    }
    
    /**
     * 编辑弟子信息
     * @param disciple 更新后的弟子对象
     * @returns 操作结果
     */
    static editDisciple(disciple: Disciple): { success: boolean; message: string } {
      const index = this.disciples.findIndex(d => d.id === disciple.id);
      if (index === -1) {
        return { success: false, message: '弟子不存在' };
      }
      
      // 检查代号是否与其他弟子重复
      if (this.disciples.some((d, i) => i !== index && d.code === disciple.code)) {
        return { success: false, message: '弟子代号已存在' };
      }
      
      // 检查姓名是否与其他弟子重复
      if (this.disciples.some((d, i) => i !== index && d.name === disciple.name)) {
        return { success: false, message: '弟子姓名已存在' };
      }
      
      this.disciples[index].name = disciple.name;
      this.disciples[index].code = disciple.code;
      this.disciples[index].star = disciple.star;

      this.saveToStorage();
      return { success: true, message: '编辑成功' };
    }
    
    /**
     * 删除弟子（移动到回收站）
     * @param id 弟子ID
     * @returns 操作结果
     */
    static deleteDisciple(id: string): { success: boolean; message: string } {
      const index = this.disciples.findIndex(d => d.id === id);
      if (index === -1) {
        return { success: false, message: '弟子不存在' };
      }
      
      const disciple = this.disciples[index];
      
      // 移动到回收站
      RecycleBinService.addToRecycleBin(disciple);
      
      // 从主列表中移除
      this.disciples.splice(index, 1);
      this.saveToStorage();
      
      return { success: true, message: '删除成功，已移动到回收站' };
    }
    
    /**
     * 为弟子添加积分记录
     * @param details 积分明细列表
     * @param discipleId 弟子ID
     * @returns 操作结果
     */
    static addScoreToDisciple(details: Detail[], discipleId: string): { success: boolean; message: string } {
      const disciple = this.getDiscipleById(discipleId);
      if (!disciple) {
        return { success: false, message: '弟子不存在' };
      }
      
      for (const detail of details) {
        let currentDate = new Date(detail.date);
        // console.log(currentDate);
        currentDate.setHours(currentDate.getHours() + 8); // 解决时区问题，确保日期正确
        detail.date = DateUtil.formatDate(currentDate);
        disciple.addDetail(detail);
      }
      
      this.saveToStorage();
      return { success: true, message: '积分添加成功' };
    }

    /**
     * 删除弟子的积分明细
     * @param discipleId 弟子ID
     * @param detailId 积分明细ID
     * @returns 操作结果
     */
    static deleteDetail(discipleId: string, detailId: string): { success: boolean; message: string } {
      const disciple = this.getDiscipleById(discipleId);
      if (!disciple) {
        return { success: false, message: '弟子不存在' };
      }

      const detailIndex = disciple.details.findIndex(d => d.id === detailId);
      if (detailIndex === -1) {
        return { success: false, message: '积分明细不存在' };
      }

      disciple.deleteDetail(detailId);
      this.saveToStorage();
      return { success: true, message: '积分明细删除成功' };
    }
    
    
    /**
     * 从本地存储加载数据
     */
    private static loadFromStorage(): void {
      try {
        const stored = localStorage.getItem(this.storageKey);
        if (stored) {
          const data = JSON.parse(stored);
          // 重新创建弟子对象以恢复方法
          this.disciples = data.map((d: any) => {
            const disciple = new Disciple(d.code, d.name, d.totalScore);
            Object.assign(disciple, d);
            return disciple;
          });
        } else {
          this.disciples = [];
        }
      } catch (error) {
        console.error('加载弟子数据失败:', error);
        this.disciples = [];
      }
    }
    
    /**
     * 保存数据到本地存储
     */
    private static saveToStorage(): void {
      try {
        localStorage.setItem(this.storageKey, JSON.stringify(this.disciples));
      } catch (error) {
        console.error('保存弟子数据失败:', error);
      }
    }
  }